package com.xl.studentpass.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xl.studentpass.entity.UserPermissionEntity;
import com.xl.studentpass.mapper.GetPermissionMapper;
import com.xl.studentpass.service.GetPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: xl
 * @createTime: 2023/5/25 09:49:37
 * @program: student-pass
 * @e-mail: 2199396150@qq.com
 * @description:
 */
@Service
@Slf4j
public class GetPermissionServiceImpl extends ServiceImpl<GetPermissionMapper, UserPermissionEntity> implements GetPermissionService {
    @Resource
    GetPermissionMapper getPermissionMapper;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Integer userId) {
        List<String> permissions = new ArrayList<>();
        List<UserPermissionEntity> userPermissions = getUserPermissions(userId);
        if (ObjectUtils.isEmpty(userPermissions) && userPermissions.size() <= 0) {
            return null;
        }
        for (UserPermissionEntity userPermission : userPermissions) {
            permissions.add(userPermission.getPermission());
        }
        return permissions;

    }

    private List<UserPermissionEntity> getUserPermissions(Integer userId) {
        LambdaQueryWrapper<UserPermissionEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPermissionEntity::getUserId, userId);
        return getPermissionMapper.selectList(wrapper);
    }


    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Integer userId) {
        ArrayList<String> roles = new ArrayList<>();
        List<UserPermissionEntity> userPermissions = getUserPermissions(userId);
        if (ObjectUtils.isEmpty(userPermissions) && userPermissions.size() <= 0) {
            return null;
        }
        for (UserPermissionEntity userPermission : userPermissions) {
            roles.add(userPermission.getPermission());
        }
        return roles;
    }
}
